package nl.han.ica.ap.searchengine.client.searching;

import java.util.ArrayList;
import java.util.List;

import nl.han.ica.ap.searchengine.client.ResultPage;
import nl.han.ica.ap.searchengine.client.SearchQuery;
import nl.han.ica.ap.searchengine.client.SearchResults;
import nl.han.ica.ap.searchengine.shared.database.DatabaseConnectionException;
import nl.han.ica.ap.searchengine.shared.database.DatabaseQueryException;
import nl.han.ica.ap.searchengine.shared.database.SearchEngineDatabase;
import nl.han.ica.ap.searchengine.shared.sdo.Webpage;

public class HtmlMatcher implements SearchStrategy {
	
	private SearchEngineDatabase sed;
	private static final String[] openTags = {"<title>","<h1>","<h2>","<h3>"};
	private static final String[] closeTags = {"</title>","</h1>","</h2>","</h3>"};

	public SearchResults process(SearchQuery query) {
		try {
			sed =  new SearchEngineDatabase();
		} catch (DatabaseConnectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		List<Webpage> webpages = null;
		try {
			webpages = sed.getAll();
		} catch (DatabaseQueryException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int currentIndex = 0;
		List<ResultPage> matchedWebpages = new ArrayList<ResultPage>();
		
		for(Webpage webpage: webpages){
			String content = webpage.getContents();
			for(int i = 0; i<openTags.length; i++){
				while(content.indexOf(openTags[i], currentIndex) != -1 ){
					int indexOfOpenTag = content.indexOf(openTags[i], currentIndex);
					int indexOfCloseTag = content.indexOf(closeTags[i], currentIndex);
					if(indexOfCloseTag != -1){
						currentIndex = indexOfCloseTag;
					}else{
						currentIndex = 0;
					}
					String subSearchString = content.substring(indexOfOpenTag+openTags[i].length(), indexOfCloseTag-closeTags[i].length());
					for(String keyWord:query.getKeywords()){
						if(subSearchString.contains(keyWord)){
							
							matchedWebpages.add(new ResultPage(webpage.getUrl()));
						}
						
					}
					
				}
				
			}
		}
		return new SearchResults(matchedWebpages);

	}

}
